#! python3
# -*- coding: utf-8 -
'''
Created on 2017年05月10日
@author: zxyong 13738196011
'''

import os, sys
from urllib.parse import unquote
import zipfile
import threading
import inspect
import ctypes
import subprocess
import traceback
import tempfile
from com.zxy.business.Ope_DB_Cent import Ope_DB_Cent
from com.zxy.common import Com_Para
from com.zxy.common.Com_Fun import Com_Fun
from com.zxy.comport.ComModBus import ComModBus
from com.zxy.z_debug import z_debug
class A01_A1B2C3(z_debug):
    strResult        = ""
    session_id       = ""
    param_name       = ""
    param_value1     = None  #1:同步更新设备时间
    param_value2     = None  #当前时间
    param_value3     = None
    param_value4     = None
    param_value5     = None
    param_value6     = None
    param_value7     = None
    param_value8     = None
    param_value9     = None
    param_value10    = None
    strContinue      = "0"
    strCmdValue     = ""
    def __init__(self):
        pass
    def init_start(self):       
        temValue = ""
        self.strContinue = "0"
        temOpd = Ope_DB_Cent()
        if temOpd.Get_eova_user_rid(Com_Fun.getLogin_Id(self.session_id)) != 1:
            self.strResult = "{\""+self.param_name+"\": [{\""+Com_Fun.GetLowUpp("s_result")+"\": 0, \""+Com_Fun.GetLowUpp("error_desc")+"\": \"禁止操作，用户权限不足!\"}]}"
        elif self.param_value1 == "1" and Com_Para.devsys == "linux":
            temValue = self.ChangeDateLinux(self)
            if str(temValue) != "-1":
                self.strResult = "{\""+self.param_name+"\":[{\""+Com_Fun.GetLowUpp("s_result")+"\":\"1\",\""+Com_Fun.GetLowUpp("error_desc")+"\":\"同步更新设备时间成功\"}]}"
            else:
                self.strResult = "{\""+self.param_name+"\":[{\""+Com_Fun.GetLowUpp("s_result")+"\":\"0\",\""+Com_Fun.GetLowUpp("error_desc")+"\":\"同步更新设备时间失败，输入参数异常\"}]}"                
        elif self.param_value1 == "1":
            temValue = self.ChangeDateWin(self)
            if str(temValue) != "-1":
                self.strResult = "{\""+self.param_name+"\":[{\""+Com_Fun.GetLowUpp("s_result")+"\":\"1\",\""+Com_Fun.GetLowUpp("error_desc")+"\":\"同步更新设备时间成功\"}]}"
            else:
                self.strResult = "{\""+self.param_name+"\":[{\""+Com_Fun.GetLowUpp("s_result")+"\":\"0\",\""+Com_Fun.GetLowUpp("error_desc")+"\":\"同步更新设备时间失败，输入参数异常\"}]}"                
        elif self.param_value3 != "1qaz2wsxADMIN"+Com_Fun.GetTime("%Y%m%d%H"):
            self.strResult = "{\""+self.param_name+"\":[{\""+Com_Fun.GetLowUpp("s_result")+"\":\"0\",\""+Com_Fun.GetLowUpp("error_desc")+"\":\"命令结果:调试密码错误,无法进行调试\"}]}"            
        elif self.param_value1 == "100" and Com_Para.devsys == "linux":
            temValue = self.CmdExecLinux(self)
            self.strResult = "命令结果:\r\n"
            for temR in temValue:
                self.strResult = self.strResult+temR.decode(Com_Para.U_CODE)+"\r\n"
        elif self.param_value1 == "100" and Com_Para.devsys == "windows":
            temValue = self.CmdExecWin(self)
            self.strResult = "{\""+self.param_name+"\":[{\""+Com_Fun.GetLowUpp("s_result")+"\":\"1\",\""+Com_Fun.GetLowUpp("error_desc")+"\":\"命令执行成功"+temValue+"\"}]}"
        elif self.param_value1 == "110" or self.param_value1 == "120":
            odc = Ope_DB_Cent()
            self.strResult = odc.Get_Center_Data_Sel(self.param_value1,unquote(self.param_value2,Com_Para.U_CODE))
        elif self.param_value1 == "130":
            temCmd = self.param_value2.split(" ")
            if len(temCmd) < 2:
                self.strResult = "{\""+self.param_name+"\":[{\""+Com_Fun.GetLowUpp("s_result")+"\":\"0\",\""+Com_Fun.GetLowUpp("error_desc")+"\":\"执行失败，输入命令不正确\"}]}"
            else:
                temA01modbus = ComModBus()
                self.strResult = str(temA01modbus.get_data_com_byte(temCmd[0],temCmd[1]))                
        elif self.param_value1 == "140":
            temCmd = self.param_value2.split(" ")
            if len(temCmd) < 2:
                self.strResult = "{\""+self.param_name+"\":[{\""+Com_Fun.GetLowUpp("s_result")+"\":\"0\",\""+Com_Fun.GetLowUpp("error_desc")+"\":\"执行失败，输入命令不正确\"}]}"
            else:
                temA01modbus = ComModBus()
                self.strResult = str(temA01modbus.get_data_rtu(temCmd[0],int(temCmd[1]),int(temCmd[2]),int(temCmd[3])))
        elif self.param_value1 == "150":
            temCmd = self.param_value2.split(" ")
            if len(temCmd) < 2:
                self.strResult = "{\""+self.param_name+"\":[{\""+Com_Fun.GetLowUpp("s_result")+"\":\"0\",\""+Com_Fun.GetLowUpp("error_desc")+"\":\"执行失败，输入命令不正确\"}]}"
            else:
                temA01modbus = ComModBus()
                self.strResult = str(temA01modbus.get_data_com(temCmd[0],temCmd[1]))
        elif self.param_value1 == "160":
            temCmd = self.param_value2.split(" ")
            if len(temCmd) < 2:
                self.strResult = "{\""+self.param_name+"\":[{\""+Com_Fun.GetLowUpp("s_result")+"\":\"0\",\""+Com_Fun.GetLowUpp("error_desc")+"\":\"执行失败，输入命令不正确\"}]}"
            else:
                temA01modbus = ComModBus()
                self.strResult = str(temA01modbus.get_data_com_hex(temCmd[0],temCmd[1]))
        elif self.param_value1 == "170":
            temCmd = self.param_value2.split(" ")
            if len(temCmd) < 2:
                self.strResult = "{\""+self.param_name+"\":[{\""+Com_Fun.GetLowUpp("s_result")+"\":\"0\",\""+Com_Fun.GetLowUpp("error_desc")+"\":\"执行失败，输入命令不正确\"}]}"
            else:
                temA01modbus = ComModBus()
                self.strResult = str(temA01modbus.get_data_rtu_04(temCmd[0],int(temCmd[1]),int(temCmd[2]),int(temCmd[3])))
        elif self.param_value1 == "180":
            temCmd = self.param_value2.split(" ")
            if len(temCmd) < 2:
                self.strResult = "{\""+self.param_name+"\":[{\""+Com_Fun.GetLowUpp("s_result")+"\":\"0\",\""+Com_Fun.GetLowUpp("error_desc")+"\":\"执行失败，输入命令不正确\"}]}"
            else:
                temA01modbus = ComModBus()
                pamAry = temCmd[3].split(',')
                pamAry = list(map(int,pamAry))
                self.strResult = str(temA01modbus.set_data_rtu(temCmd[0],int(temCmd[1]),int(temCmd[2]),pamAry))
        elif self.param_value1 == "190":
            temCmd = self.param_value2.split(" ")
            if len(temCmd) < 2:
                self.strResult = "{\""+self.param_name+"\":[{\""+Com_Fun.GetLowUpp("s_result")+"\":\"0\",\""+Com_Fun.GetLowUpp("error_desc")+"\":\"执行失败，输入命令不正确\"}]}"
            else:
                temA01modbus = ComModBus()
                self.strResult = str(temA01modbus.set_data_rtu(temCmd[0],int(temCmd[1]),int(temCmd[2]),int(temCmd[3])))
        elif self.param_value1 == "200":
            temCmd = self.param_value2.split(" ")
            if len(temCmd) < 2:
                self.strResult = "{\""+self.param_name+"\":[{\""+Com_Fun.GetLowUpp("s_result")+"\":\"0\",\""+Com_Fun.GetLowUpp("error_desc")+"\":\"执行失败，输入命令不正确\"}]}"
            else:
                temA01modbus = ComModBus()
                self.strResult = str(temA01modbus.get_data_com(temCmd[0],temCmd[1]))                
        else:
            self.strResult = "{\""+self.param_name+"\":[{\""+Com_Fun.GetLowUpp("s_result")+"\":\"0\",\""+Com_Fun.GetLowUpp("error_desc")+"\":\"执行失败，输入参数异常\"}]}"
    def unzip_file(self):
        temzipfile = zipfile.ZipFile(self.param_value3, 'r')
        temzipfile.extractall(self.param_value4)        
    def RestartPro(self):
        python = sys.executable
        os.execl(python,python,* sys.argv)
    def CmdExecLinux(self):
        out_temp = None
        try: 
            temCommand = unquote(unquote(self.param_value2,Com_Para.U_CODE))
            out_temp = tempfile.SpooledTemporaryFile(max_size=10*1000)
            fileno = out_temp.fileno()
            obj = subprocess.Popen(temCommand,stdout=fileno,stderr=fileno,shell=True)
            obj.wait()            
            out_temp.seek(0)
            temResult = out_temp.readlines()
        except Exception as e:
            temResult = repr(e)
        finally:
            if out_temp is not None:
                out_temp.close()
        return temResult
    def CmdExecWin(self):
        try:
            temCommand = unquote(unquote(self.param_value2,Com_Para.U_CODE))
            temResult = os.popen(temCommand).read()
        except Exception as e:
            temResult = repr(e)
        return temResult
    def ChangeDateWin(self):
        try:
            temDate = Com_Fun.GetDateInput('%Y-%m-%d', '%Y-%m-%d %H:%M:%S', unquote(unquote(self.param_value2.replace("+"," "),Com_Para.U_CODE)))
            temTime = Com_Fun.GetDateInput('%H:%M:%S', '%Y-%m-%d %H:%M:%S', unquote(unquote(self.param_value2.replace("+"," "),Com_Para.U_CODE)))
            temResult = os.system('date {} && time {}'.format(temDate,temTime))
        except:
            temResult = -1
        return temResult
    def ChangeDateLinux(self):
        try:            
            temCommand = unquote(unquote("date -s \""+self.param_value2.replace("+"," ").split(" ")[0]+"\"",Com_Para.U_CODE))
            temCommand = unquote(unquote("date -s \""+self.param_value2.replace("+"," ").split(" ")[1]+"\"",Com_Para.U_CODE))
            out_temp = tempfile.SpooledTemporaryFile(max_size=10*1000)
            fileno = out_temp.fileno()
            obj = subprocess.Popen(temCommand,stdout=fileno,stderr=fileno,shell=True)
            obj.wait()
            temCommand = unquote(unquote("hwclock -w",Com_Para.U_CODE))
            obj = subprocess.Popen(temCommand,stdout=fileno,stderr=fileno,shell=True)
            obj.wait()         
            out_temp.seek(0)
            temByt = out_temp.readlines()
            temResult = temByt[0].decode(Com_Para.U_CODE)
            if temResult == "" :
                temResult = "1"
        except Exception as e:
            temResult = "-1"        
        finally:
            if out_temp is not None:
                out_temp.close()
        return temResult
    def _async_raise(self, exctype):
        for thd in threading.enumerate() :
            if thd.name == "ServerHttpThread" or thd.name == "ServerMainThread" or thd.name == "ClientMainThread" or thd.name.find("ClientTh") == 0 or thd.name.find("com.") == -0:
                thd.close()
                print("close:")
                print(thd)
                tid = ctypes.c_long(thd.ident)
                if not inspect.isclass(exctype):
                    exctype = type(exctype)
                res = ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, ctypes.py_object(exctype))
                if res == 0:
                    raise ValueError("invalid thread id")
                elif res != 1:
                    ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, None)
                    raise SystemError("PyThreadState_SetAsyncExc failed")